// pages/feastPage/notOwner/notOwner.js
var netWork = require('../../../utils/netWork.js');
var api = require('../../../utils/api.js');
var apiCode = require('../../../utils/openApiCode.js');
const log = require('../../../utils/logs.js');
const QR = require('../../../utils/weapp-qrcode.js')
const regeneratorRuntime = require('../../../utils/runtime');
import {authUserPhone} from "../../../utils/publicMethods";
const {
  thirdAppId
} = require('../../../utils/api.js');
 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagesUrl: getApp().globalData.imagesUrl,
    topHeight: 0,
    isBanquetMaster: false,
    isLoading:false,
    loadingText:'',
    ani: 0, //动画是否执行
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    try {
      const {
        SDKVersion = ''
      } = wx.getSystemInfoSync();
      // 获取系统信息
      const that = this;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            addHeight: (res.screenHeight * res.pixelRatio - 1334) / 6
          });
        }
      });
      console.log(that.data.addHeight)
      log.info(SDKVersion)
      const compatibility = util.compareVersion(SDKVersion, '2.2.2');
      log.info(compatibility)
      if (compatibility == -1) {
        wx.showModal({
          content: '您的微信版本过低，请升级后再来吧~',
          confirmText: '我知道了',
          showCancel: false
        });
        return;
      }
    } catch (e) {}
    try {
      // 检测是否可以调用getUpdateManager检查更新
      if (!wx.canIUse("getUpdateManager")) return;
      let updateManager = wx.getUpdateManager();
      // 获取全局唯一的版本更新管理器，用于管理小程序更新
      updateManager.onCheckForUpdate(function (res) {
        log.info(res)
        // 监听向微信后台请求检查更新结果事件
        log.info("是否有新版本：" + res.hasUpdate);
        if (res.hasUpdate) {
          //如果有新版本
          // 小程序有新版本，会主动触发下载操作
          updateManager.onUpdateReady(function () {
            //当新版本下载完成，会进行回调
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，单击确定重启小程序',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                  updateManager.applyUpdate();
                }
              }
            })
          })
          // 小程序有新版本，会主动触发下载操作（无需开发者触发）
          updateManager.onUpdateFailed(function () {
            //当新版本下载失败，会进行回调
            wx.showModal({
              title: '提示',
              content: '检查到有新版本，但下载失败，请稍后尝试',
              showCancel: false,
            })
          })
        }
      });
    } catch (e) {
      e
    }
    //高度处理
    let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
    this.setData({
      topHeight: topHeight,
      icon: wx.getStorageSync('productType') == 4 ? 'xinyouranPage/loading_logo' : 'common/loading',
      isBanquetMaster: options.isBanquetMaster
    });
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  async getPhoneNumber(e) {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    if(e.detail.errno===1400001){
        wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.PHONENUMERROR.code + '&retMsg=' + apiCode.PHONENUMERROR.msg,
        })
        return;
    }
    this.isLoading(true, "正在获取信息...")
    var that = this;
    if (e.detail.encryptedData != undefined) {
      let res = await authUserPhone(e);
      that.isLoading(false)
      if (!res) {
        wx.redirectTo({
          url: '../../prompt/prompt?retCode=' + apiCode.AUTHFAIL.code + '&retMsg=' + apiCode.AUTHFAIL.msg,
        })
        return;
      }
      //绑定席主

      this.bindMaster();
    } else {
      that.isLoading(false)

      wx.showToast({
        title: '您拒绝了授权',
        icon: 'none'
      })

    }
  },
  bindMaster() {
    const that = this;
    netWork.POST_Json('banquet/bindMaster', {
      data: {
        userId: wx.getStorageSync('userId'),
        qrcodeAPublish: wx.getStorageSync('qrCodeFeast'),
        masterPhone: wx.getStorageSync('userPhone'),
      },
      success: function (res) {

        if (res.data.retCode == undefined) {
          wx.showToast({
            title: '操作失败，稍后重试',
            icon: 'none',
            duration:3000
          })
        }
        if (res.data.retCode == '0000') {
          wx.redirectTo({
            url: '../notActivated/notActivated?activityInfo=' + JSON.stringify(res.data.data) + '&isBanquetMaster=' + that.data.isBanquetMaster,
          })

        } else {
          wx.redirectTo({
            url: '/pages/feastPage/notThisFeast/notThisFeast?msg='+res.data.retMsg,
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '操作失败，稍后重试',
          icon: 'none',
          duration:3000
        })
      }
    });

  },
  isLoading(isLoading, loadingText) {
    this.setData({
      isLoading: isLoading,
      loadingText: loadingText
    })

  },
  /**
   * 更新用户信息
   * @param {*} encryptedData 
   * @param {*} iv 
   */
  updateUserInfo(encryptedData, iv) {
    const that = this;
    console.log('updateUserInfo')

    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          console.log("[onLoad--wx.login]" + res.code);
          if (res.code) {
            netWork.POST('updateUserInfo', {
              data: {
                userId: wx.getStorageSync('userId'),
                encryptedData: encodeURIComponent(encryptedData),
                iv: encodeURIComponent(iv),
                jsCode: res.code
              },
              success: function (res) {
                if (res.data.retCode == undefined) {
                  resolve(false);
                }
                if (res.data.retCode == '0000') {
                  wx.setStorageSync('userPhone', res.data.data.phone);
                  resolve(true);
                } else {
                  resolve(false);
                }
              },
              fail: function (res) {
                resolve(false);
              }
            });
          } else {
            console.log("获取jsCode失败" + res.errMsg);
            resolve(false);
          }
        }
      });

    });

  },
  onShow(){
    try {
        if (wx.onNeedPrivacyAuthorization) {
            wx.onNeedPrivacyAuthorization(resolve => {
                this.selectComponent('#privacyPopup').show();//这里是让组件弹窗显示
                this.selectComponent('#privacyPopup').data.parentPageInfo = this;
                this.resolvePrivacyAuthorization = resolve
            })
        }
    } catch (error) {
        console.info(error)
    }
  }
})